package com.usian.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.usian.model.admin.pojos.AdUser;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;

import com.usian.model.user.dtos.LoginDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserLoginService;
import com.usian.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ApUserLoginServiceImpl implements ApUserLoginService {

    @Autowired
    ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(LoginDto dto) {
        //1:参数校验
        if(StringUtils.isBlank(dto.getPhone())||StringUtils.isBlank(dto.getPassword())){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2:生成token
        QueryWrapper<ApUser> wrapper =new QueryWrapper<>();
        wrapper.lambda().eq(ApUser::getPhone,dto.getPhone());

        List<ApUser> userList = apUserMapper.selectList(wrapper);
        if(userList !=null && userList.size()==1 ){
            ApUser user = userList.get(0);

            //用户输入的密码 +数据库的盐值  重新生成一个pws 的加密串
            String pwd = DigestUtils.md5DigestAsHex(( dto.getPassword()+ user.getSalt()).getBytes());

            if(user.getPassword().equals(pwd)){
                //输入的密码一样   token
                //通过jwt  生成token
                String token = AppJwtUtil.getToken(user.getId().longValue());

                HashMap<String,Object> map =new HashMap<>();
                map.put("token",token);
                user.setPassword("");
                user.setSalt("");
                map.put("user",user);
                return ResponseResult.okResult(map);

            }else{
                return  ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
        }else{
            //根据设备id 0 申城token
            if(dto.getEquipmentId() == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0l));
            return ResponseResult.okResult(map);
        }
    }
}
